import { commentApi } from '@/utils/api'
import { createStore } from 'vuex'

export default createStore({
  state: {
    user: null,
    comments: []
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    setComments(state, comments) {
      state.comments = comments
    },
    addComment(state, comment) {
      state.comments.push(comment)
    },
    deleteComment(state, commentId) {
      state.comments = state.comments.filter(c => c._id !== commentId)
    }
  },
  actions: {
    async fetchComments({ commit }, { targetType, targetId }) {
      try {
        const response = await commentApi.getCommentsByTarget(targetType, targetId)
        commit('setComments', response.data)
        return response.data
      } catch (error) {
        console.error('获取评论失败:', error)
        throw error
      }
    },
    async addComment({ commit, dispatch }, { targetType, targetId, content, replyTo }) {
      try {
        await commentApi.addComment(targetType, targetId, content, replyTo)
        await dispatch('fetchComments', { targetType, targetId })
      } catch (error) {
        console.error('添加评论失败:', error)
        throw error
      }
    },
    async deleteComment({ commit, dispatch }, { commentId, targetType, targetId }) {
      try {
        await commentApi.deleteComment(commentId)
        await dispatch('fetchComments', { targetType, targetId })
      } catch (error) {
        console.error('删除评论失败:', error)
        throw error
      }
    }
  },
  getters: {
    isAuthenticated: state => !!state.user,
    currentUser: state => state.user,
    getComments: state => state.comments
  }
})
